import useRequest from "@/api/useRequest"

export class storyBoardController {
  static async rePaintStoryBoardAndCheck(storyBoardId: string, timeoutMs: number): Promise<any> {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/storyBoard/rePaintStoryBoard?storyBoardId=" + storyBoardId,
        method: "get"
      });
      const submitResult = response.data
      if (submitResult.code !== 1) {
        return {
          taskStatus: "FAILED",
          failReason: submitResult.description
        }
      }
      const taskId = response.data.result;
      let pollingInterval: number | undefined;
      let polling = true; // 添加一个轮询标志变量
      // @ts-ignore
      const pollTaskStatus = async () => {
          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/storyBoard/STORY_STABLE_DIFFUSION/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            return statusResponse.data;
          }
      };
      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      return await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject( {
              taskStatus: "FAILED",
              message: '任务超时啦！'
            });
          }, timeoutMs);
        }),
      ]);
  }



  static async asyncFooocusVaryStoryBoardAndCheck(data: any, timeoutMs: number): Promise<any> {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/storyBoard/asyncVaryUpscaleByFooocus",
        method: "post",
        data
      });
      const submitResult = response.data
      if (submitResult.code !== 1) {
        return {
          taskStatus: "FAILED",
          failReason: submitResult.description
        }
      }
      const taskId = response.data.result;
      let pollingInterval: number | undefined;
      let polling = true; // 添加一个轮询标志变量
      // @ts-ignore
      const pollTaskStatus = async () => {
        if (!polling) {
          // 如果轮询被标志为停止，则返回 null
          return null;
        }
        // 发送任务状态检查请求
        const statusResponse = await useRequest({
          url: "/storyBoard/STORY_STABLE_DIFFUSION/" + taskId + "/fetch",
          method: "get",
        });
        const status = statusResponse.data.taskStatus;
        if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
          // 继续轮询
          await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
          return pollTaskStatus(); // 继续轮询
        } else {
          clearInterval(pollingInterval);
          return statusResponse.data;
        }
      };
      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      return await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
  }



  static async asyncSDInpaintStoryBoardAndCheck(data:any, timeoutMs: number): Promise<any> {
    // 发送任务提交请求
    const response = await useRequest({
      url: "/storyBoard/inpaintImageBySD",
      method: "post",
      data
    });
    const submitResult = response.data
    if (submitResult.code !== 1) {
      return {
        taskStatus: "FAILED",
        failReason: submitResult.description
      }
    }
    const taskId = response.data.result;
    let pollingInterval: number | undefined;
    let polling = true; // 添加一个轮询标志变量
    // @ts-ignore
    const pollTaskStatus = async () => {

      if (!polling) {
        // 如果轮询被标志为停止，则返回 null
        return null;
      }
      // 发送任务状态检查请求
      const statusResponse = await useRequest({
        url: "/storyBoard/STORY_STABLE_DIFFUSION/" + taskId + "/fetch",
        method: "get",
      });
      const status = statusResponse.data.taskStatus;
      if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
        // 继续轮询
        await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
        return pollTaskStatus(); // 继续轮询
      } else {
        clearInterval(pollingInterval);
        return statusResponse.data;
      }
    };
    // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
    return await Promise.race([
      pollTaskStatus(),
      new Promise((_, reject) => {
        setTimeout(() => {
          clearInterval(pollingInterval)
          polling = false
          reject(new Error("任务超时"));
        }, timeoutMs);
      }),
    ]);
  }

  static async asyncFooocusInpaintStoryBoardAndCheck(data:any, timeoutMs: number): Promise<any> {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/storyBoard/inpaintImageByFooocus",
        method: "post",
        data
      });
      const submitResult = response.data
      if (submitResult.code !== 1) {
        return {
          taskStatus: "FAILED",
          failReason: submitResult.description
        }
      }
      const taskId = response.data.result;
      let pollingInterval: number | undefined;
      let polling = true; // 添加一个轮询标志变量
      // @ts-ignore
      const pollTaskStatus = async () => {

          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/storyBoard/STORY_STABLE_DIFFUSION/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            return statusResponse.data;
          }
      };
      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      return await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
  }


  static async asyncFooocusExpandStoryBoardAndCheck(expandDirection:string,storyBoardId:string, timeoutMs: number): Promise<any> {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/storyBoard/expandImageByFooocus?expandDirection="+expandDirection+"&storyBoardId="+storyBoardId,
        method: "get"
      });
      const submitResult = response.data
      if (submitResult.code !== 1) {
        return {
          taskStatus: "FAILED",
          failReason: submitResult.description
        }
      }
      const taskId = response.data.result;
      let pollingInterval: number | undefined;
      let polling = true; // 添加一个轮询标志变量
      // @ts-ignore
      const pollTaskStatus = async () => {
          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/storyBoard/STORY_STABLE_DIFFUSION/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            return statusResponse.data;
          }
      };
      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      return await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
  }



  static async reTtsStoryBoardAndCheck(storyBoardId:string,  timeoutMs: number): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/storyBoard/reTtsStoryBoard?storyBoardId="+storyBoardId,
        method: "get"
      });
      const taskId = response.data.result;
      let pollingInterval: number | undefined;
      let polling = true; // 添加一个轮询标志变量
      // @ts-ignore
      const pollTaskStatus = async () => {
        try {
          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/storyBoard/STORY_TEXT_TO_AUDIO/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 2000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            if (status === "SUCCESS") {
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };
      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      return await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
    } catch (error) {
      throw new Error("提交任务失败");
    }
  }



  // 重绘本镜
  static rePaintStoryBoard(storyBoardId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/rePaintStoryBoard?storyBoardId=" + storyBoardId,
      method: "get"
    })
  }


  static boardByParagraph(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/boardByParagraph",
      method: "post",
      data
    })
  }


  static transToEnglish(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/transToEnglish",
      method: "post",
      data
    })
  }

  static deleteBoard(storyBoardId: string, chapterId: string): Promise<any> {
    const data = {
      boardId: storyBoardId,
      chapterId: chapterId
    }
    return useRequest({
      url: "/storyBoard/deleteBoard",
      method: "post",
      data
    })
  }


  static addOrUpdateBoard(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/addOrUpdateBoard",
      method: "post",
      data
    })
  }


  static addOrUpdateBoards(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/addOrUpdateBoards",
      method: "post",
      data
    })
  }

  static getStoryBoardPrompt(storyBoardId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/getStoryBoardPrompt?storyBoardId=" + storyBoardId,
      method: "get"
    })
  }

  static initializationVideoStoryBoard(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/initializationVideoStoryBoard",
      method: "post",
      data
    })
  }

  static interrogate(storyBoardId: string,modelName?:string): Promise<any> {
    return useRequest({
      url: "/storyBoard/interrogate?storyBoardId=" + storyBoardId +"&modelName="+modelName,
      method: "get"
    })
  }

  static async upscale(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/upscale",
      method: "post",
      data
    })
  }


  static async upscaleByFooocus(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/upscaleByFooocus",
      method: "post",
      data
    })
  }


  static async expandImage(storyBoardId: string, expandDirection: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/expandImage?expandDirection="+expandDirection+"&storyBoardId="+storyBoardId,
      method: "get"
    })
  }



  static cleanUpWaterMarker(data:any): Promise<any> {
    return useRequest({
      url: "/storyBoard/waterMarkerCleanUp",
      method: "post",
      data
    })
  }

  static uploadStoryBoardImage(data:any): Promise<any> {
    return useRequest({
      url: "/storyBoard/uploadImage",
      method: "post",
      data
    })
  }

  static updateByOrderNum(data:any): Promise<any> {
    return useRequest({
      url: "/story/updateByOrderNum",
      method: "post",
      data
    })
  }
}

